package cn.fengwoo.springBoot.service.impl;


import cn.fengwoo.springBoot.dao.UserDao;
import cn.fengwoo.springBoot.entity.User;
import cn.fengwoo.springBoot.repository.UserRepository;
import cn.fengwoo.springBoot.service.TokenService;
import cn.fengwoo.springBoot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.UnknownHostException;
import java.util.List;


/**
 * Created by fangdaji on 2018/1/10.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRepository repository;

    @Autowired
    private TokenService tokenService;



    /**
     * 注册（保存）
     * @param user
     */
    public User register(User user) {
        List<User> byName = repository.findByName(user.getName());
        if(byName!=null&&byName.size()>0){
            return null;
        }

        User newUser = repository.save(user);
        System.out.println("注册:"+newUser.toString());

        return newUser;
    }

    /**
     * 登录（条件查询）
     * @param user
     * @return
     */
    public User login(User user){
        userDao.select();


        Example<User> ex = Example.of(user);
        User one = repository.findOne(ex);

        if(one!=null){

            // 更新token
            try {
                String token = tokenService.generateToken(one.getId(),one.getName());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }

            return one;
        }

        return null;
    }

    /**
     * 用户列表（查询列表）
     * @return
     */
    public List<User> userList(){
        List<User> all = repository.findAll();



        return all;
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    public User changePassword(User user){
        User user1 = repository.saveAndFlush(user);
        return user1;
    }

    /**
     * 删除用户
     * @param user
     */
    public void deleteUser(User user){

    }
}
